package com.qi.config;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.lang.Dict;
import cn.hutool.setting.yaml.YamlUtil;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.qi.pojo.Configuration;

import java.beans.PropertyVetoException;
import java.util.HashMap;

/**
 * @author zjq
 * @version 1.0
 * @date 2021/12/5 14:15
 */
public class YamlConfigBuilder {
    private Configuration configuration;

    public YamlConfigBuilder() {
        this.configuration = configuration;
    }

    /**
     * 从yaml文件中加载数据源配置信息
     *
     * @param filePath
     * @return
     * @throws PropertyVetoException
     */
    public Configuration loadYamlConfig(String filePath) throws PropertyVetoException {
        //获取数据源配置信息信息
        ClassPathResource classPathResource = new ClassPathResource(filePath);
        Dict yamlDict = YamlUtil.load(classPathResource.getStream(), Dict.class);
        HashMap springDatasource = yamlDict.getByPath("spring.datasource", HashMap.class);
        // 使用连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass((String) springDatasource.get("driver-class-name"));
        dataSource.setJdbcUrl((String) springDatasource.get("url"));
        dataSource.setUser((String) springDatasource.get("username"));
        dataSource.setPassword((String) springDatasource.get("password"));

        configuration.setDataSource(dataSource);
        return configuration;
    }
}
